#include <buola/gui/containers/cmosaiccontainer.h>

#include <buola/image/cfont.h>
#include <buola/image/cgc.h>

namespace buola { namespace gui {

CMosaicContainer::CMosaicContainer()
    :   mNumRows(2)
    ,   mMargin(10)
    ,   mFont(img::CFont::GetStock(L"nicetitle"))
{
    SetBackColor(img::CColor(0.8,0.9,1.0));
}

CMosaicContainer::~CMosaicContainer()
{
}

void CMosaicContainer::SetNumRows(int pNumRows)
{
    mNumRows=pNumRows;
}

void CMosaicContainer::SetMargin(double pMargin)
{
    mMargin=pMargin;
}

void CMosaicContainer::Add(const PWindow &pWindow)
{
    Manage(pWindow);
    Refresh();
}

void CMosaicContainer::OnLayout()
{
    const std::vector<PWindow> &lChildren=ManagedChildren();
    
    int lRow=0;
    CPoint_d lPos(mMargin,mFont->GetHeight()+mMargin);
    double lMaxHeight=0;
    
    for(const PWindow &c : lChildren)
    {
        CSize_d lSize=c->PreferredSize();
        if(lSize.Undefined()) lSize={640,480};
        
        c->Map(lPos,lSize);
        lMaxHeight=std::max(lMaxHeight,lSize.y);
        
        lRow++;
        if(lRow==mNumRows)
        {
            lRow=0;
            lPos.x=mMargin;
            lPos.y+=lMaxHeight+mFont->GetHeight()+mMargin;
        }
        else
        {
            lPos.x+=lSize.x+mMargin;
        }
    }
}

void CMosaicContainer::OnExpose(const CExposeEvent &pE)
{
    const std::vector<PWindow> &lChildren=ManagedChildren();

    for(const PWindow &c : lChildren)
    {
        pE.mGC->SetFont(mFont);
        pE.mGC->DrawText(c->Position()-CPoint_d(0,mFont->GetHeight()),c->Title());
    }
}

/*namespace gui*/ } /*namespace buola*/ }
